package com.dajingling.controller;

import com.dajingling.bean.Message;
import com.dajingling.mvc.ResponseBody;
import com.dajingling.mvc.ResponseView;
import com.dajingling.service.AdminService;
import com.dajingling.util.JSONUtil;
import com.dajingling.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

public class AdminController {
    @ResponseBody("/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        //1.接收参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.调用service传参数，并获取结果
        //先访问普通用户数据库
        boolean result = AdminService.login(username,password);
        //3.根据结果，返回不同的数据给ajax
        //并且告诉ajax当前用户是普通用户还是管理员用户
        Message msg = null;
        if (result){
            msg = new Message(0,"登录成功！");
            Date date = new Date();
            String ip = request.getRemoteAddr();
            AdminService.updateLoginTimeAndIP(username,date,ip);
            request.getSession().setAttribute("adminUserName",username);
        }else {
            msg = new Message(-1,"登录失败！");
        }
        //4.将数据转换为json
        String json = JSONUtil.toJSON(msg);
        //5.将json回复给ajax
        System.out.println("前台登录："+json);
        return json;
    }

    @ResponseView("/admin/loginout.do")
    public String loginOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        String username = UserUtil.getUserName(session);
        session.invalidate();
        //删除所有值
        System.out.println("用户："+username+",已退出登录");
        return "/index.jsp";
    }
}
